#include "control.h"
#include <stdio.h>
#include "data_manager.h"
#include "lvgl/lvgl.h"
#include "ui/ui.h"
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include "tires.h"
#include <sys/stat.h>
#include <time.h>
#include <math.h>
#include <errno.h>
#include "indicators.h"
#include "data_manager.h"
#include "ui/screens/ui_xsjlwin.h"
#include "lvgl/src/extra/widgets/msgbox/lv_msgbox.h"
#include "main.h"
#include <stdatomic.h>
#include <pthread.h>
#include "ui_message_handler.h"
#include "ui_message.h"


static bool small_font_initialized = false;

static void update_date_ui_async(void *date_buf);

// LVGL 版本兼容性处理
#if !LV_VERSION_CHECK(8, 0, 0)
// LVGL 7.x 兼容性函数
static inline bool lv_style_is_invalid(const lv_style_t * style) {
    return style == NULL;
}

static inline int lv_style_get_prop_cnt(const lv_style_t * style) {
    return style != NULL ? 1 : 0;
}
#endif

lv_style_t small_font_style;

static void start_right_signal_anim(void *arg);
static void stop_right_signal_anim(void *arg);

// 定义共享变量
DisplayMode current_mode = CONSOLE_MODE;

  void init_small_font_style(void) {
      if (!small_font_initialized && lv_is_initialized()) {
          lv_style_init(&small_font_style);
      lv_style_set_text_font(&small_font_style, &ui_font_smallfont);
          small_font_initialized = true;
      }
  }
  
#if LV_VERSION_MAJOR >= 8
#define STYLE_SELECTOR(part, state) (part | state)
#else
#define STYLE_SELECTOR(part, state) part
#endif
// UI元素外部声明
extern lv_obj_t *ui_Label8;
extern lv_obj_t *ui_Label18;
extern lv_obj_t *ui_Label19;
extern lv_obj_t *ui_Label20;
extern lv_obj_t *ui_date2;

// 定义数据目录和文件名
#define DATA_DIR_NAME "car_dashboard_data"
#define DATA_FILE_NAME "driving_data.txt"

#define CLAMP(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))

SystemState system_state = {0};

//外部引用data_manager中定义的全局变量
extern DrivingData data_backup;

// 全局互斥锁定义
static pthread_mutex_t lv_mutex;
pthread_mutex_t indicator_mutex;


static pthread_once_t mutex_init_once = PTHREAD_ONCE_INIT;
void initialize_mutexes(void);

void Control_Init(void);

static bool menu_printed = false;

// 静态样式初始化函数
// 确保样式只初始化一次
static pthread_once_t style_init_once = PTHREAD_ONCE_INIT;

void init_style_safe(void) {
    pthread_once(&style_init_once, init_style);
}
static void init_style(void) {
    // 重置并初始化样式
    lv_style_reset(&small_font_style);
    lv_style_init(&small_font_style);
    // 验证样式初始化结果
    // LVGL v7兼容的样式初始化检查
    if (small_font_style.prop_cnt == 0) {

        log_message(LOG_ERROR, "Failed to initialize small_font_style");
        return;
    }
    const lv_font_t *font = &ui_font_smallfont;
    // 增强字体有效性检查，确保关键函数指针有效
    if (!font || !font->get_glyph_dsc) {
        font = lv_font_default();
    }
    lv_style_set_text_font(&small_font_style, font);

    // 样式应用前完整有效性检查
    static bool styles_applied = false;

    // 添加样式内存地址范围检查
    if(lv_is_initialized() && !styles_applied) {
        int max_attempts = 5;
        int attempt = 0;
        const int delay_ms = 100;
        bool all_valid = false;

        while (attempt < max_attempts && !all_valid) {
            all_valid = true;
            attempt++;

            if(pthread_mutex_lock(&lv_mutex) == 0) { // 添加互斥锁保护UI操作

                all_valid = true;

                pthread_mutex_unlock(&lv_mutex); // 释放互斥锁
            } else {
                log_message(LOG_ERROR, "Failed to lock LVGL mutex (attempt %d)", attempt);
                all_valid = false;
            }

            if (!all_valid && attempt < max_attempts) {
                log_message(LOG_INFO, "Retrying style application in %dms...", delay_ms);
                lv_task_handler(); // 处理LVGL任务
                usleep(delay_ms * 1000); // 等待UI初始化
            }
        }

        if (all_valid) {
            log_message(LOG_INFO, "Styles applied successfully after %d attempts", attempt);
            styles_applied = true;
        } else {
            log_message(LOG_ERROR, "Failed to apply styles after %d attempts", max_attempts);
        }
    } else {
        if (!lv_is_initialized()) {
            log_message(LOG_ERROR, "LVGL not initialized");
        } else if (styles_applied) {
            log_message(LOG_INFO, "Styles already applied");
        }
    }
}

// 错误处理函数
void ErrorExit(const char *lpszFunction, int error);

// 初始化互斥锁
void Control_Init(void) {
    // pthread_once(&mutex_init_once, initialize_mutexes);
    // 1. 初始化互斥锁
    init_mutex();
    
    // 2. 确保LVGL已初始化
    if(!lv_is_initialized()) {
        printf("\n");
        return;
    }
    init_weather_service(); // 添加天气服务初始化
}

void initialize_mutexes(void) {    small_font_initialized = false;
    // 初始化字体样式
    lv_style_init(&small_font_style);
    lv_style_set_text_font(&small_font_style, lv_font_default()); // 调用默认字体函数获取字体实例
    small_font_initialized = true;
    // 初始化互斥锁
    int err;
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
    
    if ((err = pthread_mutex_init(&lv_mutex, &attr)) != 0) {
        ErrorExit("pthread_mutex_init for lv_mutex", err);
    }
    
    if ((err = pthread_mutex_init(&system_state.data_mutex, &attr)) != 0) {
        ErrorExit("pthread_mutex_init for data_mutex", err);
    }
    if ((err = pthread_mutex_init(&indicator_mutex, &attr)) != 0) {
        ErrorExit("pthread_mutex_init for indicator_mutex", err);
    }
    
    pthread_mutexattr_destroy(&attr);
}

void init_mutex(void) {
    pthread_once(&mutex_init_once, initialize_mutexes);
}

// 错误处理函数
void ErrorExit(const char *lpszFunction, int error) {
    fprintf(stderr, "%s failed with error %d: %s\n", lpszFunction, error, strerror(error));
    exit(EXIT_FAILURE);
}

SystemState *get_system_state(void)
{
    return &system_state;
}

/* 异步回调实现 */
static void async_generate_data_cb(void *param) {
    (void)param;
    
    if (atomic_load(&data_generation_in_progress)) {
        log_message(LOG_DEBUG, "数据生成已在进行，跳过异步回调");
        return;
    }
    
    atomic_store(&data_generation_in_progress, true);
    
    if (!generate_driving_data()) {
        log_message(LOG_ERROR, "异步数据生成失败");
    }
    
    if (!save_driving_data(true)) {
        log_message(LOG_ERROR, "异步数据保存失败");
    }
    
    safe_async_call((void(*)(void*))update_display, NULL);
    atomic_store(&data_generation_in_progress, false);
}

// 全局状态初始化
_Atomic int msgbox_active_flag = 0;

void reset_and_update_data(void *param) {
    int err;
    log_message(LOG_DEBUG, "Entering reset_and_update_data");

    static bool in_reset = false;
    if (in_reset) return;
    in_reset = true;

    // 1. 快速获取数据快照
    DrivingData snapshot;
    if ((err = pthread_mutex_lock(&system_state.data_mutex)) != 0) { ErrorExit("pthread_mutex_lock failed", err); }
    memcpy(&snapshot, &system_state.current_data, sizeof(DrivingData));
    if ((err = pthread_mutex_unlock(&system_state.data_mutex)) != 0) { ErrorExit("pthread_mutex_unlock failed", err); }

    // 2. 重置所有数据（包括总里程）
    snapshot.driving_distance = 0;
    snapshot.driving_time = 0;
    snapshot.fuel_consumption = 0.0f;
    snapshot.total_distance = 0;
    snapshot.last_update = time(NULL);

    // 3. 原子化提交
    pthread_mutex_lock(&system_state.data_mutex);
    memcpy(&system_state.current_data, &snapshot, sizeof(DrivingData));
    pthread_mutex_unlock(&system_state.data_mutex);

    // 4. 保存数据并异步更新UI
    save_driving_data(false);
    lv_async_call(update_display, NULL);

    in_reset = false;
}

void emergency_recovery(void) {
    int err;
    log_message(LOG_DEBUG, "Entering emergency_recovery");
    if ((err = pthread_mutex_trylock(&system_state.data_mutex)) == 0) {
        pthread_mutex_unlock(&system_state.data_mutex);
    } else {
        log_message(LOG_ERROR, "Failed to lock mutex for emergency recovery");
        return;
    }
}

bool try_lock_with_timeout(pthread_mutex_t *mutex, int timeout_ms) {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_nsec += timeout_ms * 1000000;
    
    int res = pthread_mutex_timedlock(mutex, &ts);
    return (res == 0);
}

size_t get_available_memory(void) {
    int err;
    lv_mem_monitor_t info;
    if ((err = pthread_mutex_lock(&lv_mutex)) != 0) { ErrorExit("pthread_mutex_lock failed in get_available_memory", err); }
    lv_mem_monitor(&info);
    if ((err = pthread_mutex_unlock(&lv_mutex)) != 0) { ErrorExit("pthread_mutex_unlock failed in get_available_memory", err); }
    return info.free_size;
}

bool ensure_memory_available(size_t required) {
    lv_mem_monitor_t info;
    pthread_mutex_lock(&lv_mutex);
    lv_mem_monitor(&info);
    pthread_mutex_unlock(&lv_mutex);
    return info.free_size >= required;
}


// 切换显示模式
void switch_display_mode(DisplayMode new_mode) {
    current_mode = new_mode;
    if (new_mode == CONSOLE_MODE) {
        // 显示控制台，隐藏数据页面
        printf("\n======= 车载仪表控制台 =======\n");
        printf("设置速度: speed [0-240]\n");
        printf("设置转速: rev [0-8000]\n");
        printf("换挡: p(驻车)/r(倒车)/n(空挡)/d(前进)/s(运动)\n");
        printf("驾驶模式: 0(普通)/1(环保)/2(竞速)/3(夜间)/4(智能)\n");
        printf("指示灯控制: on/off [指示灯名称]\n");
        printf("左转向灯开启/关闭: on zuosan/off zuosan\n");
        printf("右转向灯开启/关闭: on yousan/off yousan\n");
        printf("双闪灯开启/关闭: on shuangshan/off shuangshan\n");
        printf("设置冷却液温度:coolant[0-120]\n");
        printf("请输入命令(youhao [0.0-1.0]):\n");
        printf("轮胎设置: tire [位置(1-4)] [胎压] [温度]\n");
        printf("查看数据: check shuju\n");
        printf("退出: q 或 exit\n");
        printf("输入命令: ");
        fflush(stdout);
    } else {
        // 显示数据页面，隐藏控制台
        printf("\n======= 行驶数据页面 =======\n");
        printf("当前行驶数据:\n");
        printf("距离: %d km\n", system_state.current_data.driving_distance);
        printf("时间: %d min\n", system_state.current_data.driving_time);
        printf("油耗: %.1f L/100km\n", system_state.current_data.fuel_consumption);
        printf("总里程: %d km\n", system_state.current_data.total_distance);
        printf("\n输入命令 'fanhui' 返回控制台\n");
        printf("输入命令: ");
        fflush(stdout);
    }
}

// 原子化UI更新宏（带安全校验）
#define SAFE_UPDATE_LABEL(obj, fmt, ...) do { \
    if ((obj) && lv_obj_is_valid(obj)) { \
        char buf[32]; \
        snprintf(buf, sizeof(buf), fmt, ##__VA_ARGS__); \
        if(pthread_mutex_lock(&lv_mutex) == 0) { \
            lv_label_set_text(obj, buf); \
            pthread_mutex_unlock(&lv_mutex); \
        } \
    } \
} while(0)

// 更新UI显示函数
void update_display(void *param)
  {
    static lv_style_t style;  // 必须静态或全局
    static bool style_initialized = false;
    (void)param; // 明确标记未使用参数
    int err;
    DrivingData data;

    // 使用线程安全的UI更新API
    char date_buf[32];
    time_t current_time = time(NULL);
    struct tm *tm_info = localtime(&current_time);
    if (tm_info) {
        strftime(date_buf, sizeof(date_buf), "%y年%m月%d日", tm_info);
        safe_label_set_text(ui_date2, date_buf);
    }
    
    // 1. 准备静态资源（线程安全的单例初始化）
      if (!style_initialized) {
          lv_style_init(&style);
          lv_style_set_bg_color(&style, lv_color_hex(0x123456));
          style_initialized = true;
      }

      // 获取目标UI对象并检查有效性
      lv_obj_t *target_obj = lv_scr_act();
      if(!target_obj) {
          log_message(LOG_ERROR, "无效的UI目标对象");
          return;
      }

    // 2. 安全获取数据快照（毫秒级锁持有）
    SystemState *state = get_system_state();
    if (!state) {
        log_message(LOG_ERROR, "[UI] Invalid system state");
        return;
    }

    if ((err = pthread_mutex_lock(&state->data_mutex)) != 0) { 
        ErrorExit("pthread_mutex_lock failed in update_display", err); 
        log_message(LOG_ERROR, "[UI] Mutex lock failed");
        return;
    }
    
    // 内存拷贝比直接赋值更安全（避免结构体对齐问题）
    memcpy(&data, &state->current_data, sizeof(DrivingData));
    if ((err = pthread_mutex_unlock(&state->data_mutex)) != 0) { 
        ErrorExit("pthread_mutex_unlock failed in update_display", err); 
    }

    // 3. 数据预处理（非关键路径不阻塞UI线程）
    data.driving_distance = CLAMP(data.driving_distance, 0, 9999);
    data.driving_time = CLAMP(data.driving_time, 0, 99 * 60);

    // 5. 关键字段更新（按显示区域分组）
    // 5.1 里程信息组
    SAFE_UPDATE_LABEL(ui_Label8, "%d", data.driving_distance);
    
    // 5.2 时间信息组（格式化为HH:MM）
    int hours = data.driving_time / 60;
    int minutes = data.driving_time % 60;
    SAFE_UPDATE_LABEL(ui_Label18, "%02d:%02d", hours, minutes);

    // 5.3 油耗信息组
    SAFE_UPDATE_LABEL(ui_Label19, "%.1f", data.fuel_consumption);

    // 5.4 总里程信息组（千位分隔符处理）
    // 确保显示值不超过15000
    int displayed_total = data.total_distance > 15000 ? 15000 : data.total_distance;
    SAFE_UPDATE_LABEL(ui_Label20, "%d,%03d", 
                     displayed_total / 1000,
                     displayed_total % 1000);

    // 6. 日期显示（独立校验）
    if (ui_date2 && lv_obj_is_valid(ui_date2)) {
        char date_buf[32];
        time_t now = time(NULL);
        struct tm *tm_info = localtime(&now);
        if (tm_info) {
            strftime(date_buf, sizeof(date_buf), "%y年%m月%d日", tm_info);
              // 确保样式和互斥锁已初始化
              pthread_once(&mutex_init_once, initialize_mutexes);
              // 使用safe_async_call在主线程更新UI
            char *date_buf_dup = strdup(date_buf);
            safe_async_call((void (*)(void*))update_date_ui_async, date_buf_dup);
        }
    }

    // 7. 强制重绘（但限制频率）
    static uint32_t last_refresh = 0;
    uint32_t tick_now = lv_tick_get();
    if (tick_now - last_refresh > 33) { // 约30FPS
        lv_refr_now(NULL);
        last_refresh = tick_now;
    }

    // 8. 错误恢复记录
    static int error_count = 0;
    if (!lv_obj_is_valid(lv_scr_act())) {
        if (++error_count > 3) {
            emergency_recovery();
        }
    } else {
        error_count = 0;
    }
}

static void delayed_update_timer(lv_timer_t *timer) {
    update_display(NULL);
    lv_refr_now(NULL);
    lv_timer_del(timer);
}

// 命令处理函数
bool process_command(const char *cmd) {
    if (strcmp(cmd, "check shuju") == 0) {
        switch_display_mode(DATA_VIEW_MODE);
        // lv_timer_create(delayed_update_timer, 200, NULL);
        return true;
    } else if (strcmp(cmd, "fanhui") == 0) {
        switch_display_mode(CONSOLE_MODE);
        // lv_timer_create(delayed_update_timer, 200, NULL);
        print_console_menu();
        return true;
    }

    return false;
}

/* 左转向灯动画回调声明 */
static void left_signal_anim_cb(lv_anim_t *a);
/* 左转向灯UI动画实现 */
static void left_signal_anim_ui(void* arg) {
    if (left_turn_signal_on || hazard_lights_on) {
        if (lv_obj_is_visible(ui_zxdon2)) {
            lv_obj_add_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
        } else {
            lv_obj_add_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
        }
        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, ui_zxdon2);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_ready_cb(&anim, left_signal_anim_cb);
        lv_anim_start(&anim);
    }
}

/* 左转向灯停止UI实现 */
static void left_signal_stop_ui(void* arg) {
    lv_obj_add_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
    is_left_signal_animating = false;
}

/* 左转向灯动画回调 */
static void left_signal_anim_cb(lv_anim_t *a)
{
    pthread_mutex_lock(&indicator_mutex);
    bool left_on = left_turn_signal_on;
    bool hazard_on = hazard_lights_on;
    pthread_mutex_unlock(&indicator_mutex);
    
    if (left_on || hazard_on)
    {
        if (lv_obj_is_visible(ui_zxdon2))
        {
            lv_obj_add_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
        }
        else
        {
            lv_obj_add_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
        }

        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, ui_zxdon2);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_ready_cb(&anim, left_signal_anim_cb);
        lv_anim_start(&anim);
    }
    else
    {
        lv_obj_add_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
        pthread_mutex_lock(&indicator_mutex);
        is_left_signal_animating = false;
        pthread_mutex_unlock(&indicator_mutex);
    }
}

/* 右转向灯动画回调声明 */
static void right_signal_anim_cb(lv_anim_t *a);
/* 右转向灯UI动画实现 */
static void right_signal_anim_ui(void* arg) {
    if (right_turn_signal_on || hazard_lights_on) {
        if (lv_obj_is_visible(ui_yxdon2)) {
            lv_obj_add_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
        } else {
            lv_obj_add_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
        }
        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, ui_yxdon2);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_ready_cb(&anim, right_signal_anim_cb);
        lv_anim_start(&anim);
    }
}

/* 右转向灯停止UI实现 */
static void right_signal_stop_ui(void* arg) {
    lv_obj_add_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
    is_right_signal_animating = false;
}

/* 右转向灯动画回调 */
static void right_signal_anim_cb(lv_anim_t *a)
{
    pthread_mutex_lock(&indicator_mutex);
    bool right_on = right_turn_signal_on;
    bool hazard_on = hazard_lights_on;
    pthread_mutex_unlock(&indicator_mutex);
    
    if (right_on || hazard_on)
    {
        if (lv_obj_is_visible(ui_yxdon2))
        {
            lv_obj_add_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
        }
        else
        {
            lv_obj_add_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
        }

        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, ui_yxdon2);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_ready_cb(&anim, right_signal_anim_cb);
        lv_anim_start(&anim);
    }
    else
    {
        lv_obj_add_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
        pthread_mutex_lock(&indicator_mutex);
        is_right_signal_animating = false;
        pthread_mutex_unlock(&indicator_mutex);
    }
}

/* 左转向灯动画控制函数 */
static void start_left_signal_anim(void *arg)
{
    (void)arg;
    pthread_mutex_lock(&indicator_mutex);
    if (!is_left_signal_animating)
    {
        is_left_signal_animating = true;
        pthread_mutex_unlock(&indicator_mutex);
        lv_obj_add_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);

        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, ui_zxdon2);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_ready_cb(&anim, left_signal_anim_cb);
        lv_anim_start(&anim);
    }
    else
    {
        pthread_mutex_unlock(&indicator_mutex);
    }
}

static void stop_left_signal_anim(void *arg)
{
    (void)arg;
    lv_obj_add_flag(ui_zxdon2, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(ui_zxdoff1, LV_OBJ_FLAG_HIDDEN);
    pthread_mutex_lock(&indicator_mutex);
    is_left_signal_animating = false;
    pthread_mutex_unlock(&indicator_mutex);
}

/* 双闪动画同步启动函数 */
static void start_hazard_animations(void *arg)
{
    start_left_signal_anim(NULL);
    start_right_signal_anim(NULL);
}

/* 双闪动画同步停止函数 */
static void stop_hazard_animations(void *arg)
{
    // 删除动画并停止转向灯
    lv_anim_del(ui_zxdon2, NULL);
    lv_anim_del(ui_yxdon2, NULL);
    stop_left_signal_anim(NULL);
    stop_right_signal_anim(NULL);
}

/* 右转向灯动画控制函数 */
static void start_right_signal_anim(void *arg)
{
    (void)arg;
    pthread_mutex_lock(&indicator_mutex);
    if (!is_right_signal_animating)
    {
        is_right_signal_animating = true;
        pthread_mutex_unlock(&indicator_mutex);
        lv_obj_add_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);

        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, ui_yxdon2);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_ready_cb(&anim, right_signal_anim_cb);
        lv_anim_start(&anim);
    }
    else
    {
        pthread_mutex_unlock(&indicator_mutex);
    }
}

static void stop_right_signal_anim(void *arg)
{
    (void)arg;
    lv_obj_add_flag(ui_yxdon2, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(ui_yxdoff1, LV_OBJ_FLAG_HIDDEN);
    pthread_mutex_lock(&indicator_mutex);
    is_right_signal_animating = false;
    pthread_mutex_unlock(&indicator_mutex);
}

/* 左转向灯开关控制 */
bool toggle_left_turn_signal(bool enable)
{
    pthread_mutex_lock(&indicator_mutex);
    bool current_hazard = hazard_lights_on;
    bool current_state = left_turn_signal_on;
    pthread_mutex_unlock(&indicator_mutex);

    if (enable && current_hazard)
    {
        toggle_hazard_lights(false);
        return true;
    }

    if (!current_hazard && enable == current_state)
        return false;

    pthread_mutex_lock(&indicator_mutex);
    left_turn_signal_on = enable;
    pthread_mutex_unlock(&indicator_mutex);

    if (enable && !is_left_signal_animating)
    {
        safe_async_call((void(*)(void*))start_left_signal_anim, NULL);
    } else if (!enable)
    {
        safe_async_call((void(*)(void*))stop_left_signal_anim, NULL);
    }
    return true;
}

/* 右转向灯开关控制 */
bool toggle_right_turn_signal(bool enable)
{
    pthread_mutex_lock(&indicator_mutex);
    bool current_hazard = hazard_lights_on;
    bool current_state = right_turn_signal_on;
    pthread_mutex_unlock(&indicator_mutex);

    if (enable && current_hazard)
    {
        toggle_hazard_lights(false);
        return true;
    }

    if (!current_hazard && enable == current_state)
        return false;

    pthread_mutex_lock(&indicator_mutex);
    right_turn_signal_on = enable;
    pthread_mutex_unlock(&indicator_mutex);

    if (enable && !is_right_signal_animating)
    {
        safe_async_call((void(*)(void*))start_right_signal_anim, NULL);
    } else if (!enable)
    {
        safe_async_call((void(*)(void*))stop_right_signal_anim, NULL);
    }
    return true;
}

/* 双闪控制函数 */
bool toggle_hazard_lights(bool enable)
{
    pthread_mutex_lock(&indicator_mutex);
    if (enable == hazard_lights_on) {
        pthread_mutex_unlock(&indicator_mutex);
        return false;
    }

    hazard_lights_on = enable;
        shuangshan_on = enable; // 同步双闪灯状态变量
        if (!enable) {
            left_turn_signal_on = false;
            right_turn_signal_on = false;
        }
    pthread_mutex_unlock(&indicator_mutex);
    
    // 更新指示灯UI
    safe_async_call((void(*)(void*))update_all_indicators, NULL);
    
    if (enable) {
        // 停止单独转向灯动画
        pthread_mutex_lock(&indicator_mutex);
        if (left_turn_signal_on) {
            lv_anim_del(ui_zxdon2, NULL);
            left_turn_signal_on = false;
        }
        if (right_turn_signal_on) {
            lv_anim_del(ui_yxdon2, NULL);
            right_turn_signal_on = false;
        }

        // 直接设置转向灯状态并启动动画
        left_turn_signal_on = true;
        right_turn_signal_on = true;
        pthread_mutex_unlock(&indicator_mutex);

        // 同步启动双闪动画
        safe_async_call((void(*)(void*))start_hazard_animations, NULL);
    } else {
        // 直接关闭转向灯并停止动画
        pthread_mutex_lock(&indicator_mutex);
        left_turn_signal_on = false;
        right_turn_signal_on = false;
        pthread_mutex_unlock(&indicator_mutex);

        // 同步停止双闪动画并删除残留回调
        safe_async_call((void(*)(void*))stop_hazard_animations, NULL);
    }
    return true;
}

/* 日期UI异步更新函数声明 */
static void update_date_ui_async(void *arg);

/* 日期UI异步更新函数 */
static void update_date_ui_async(void *arg) {
    char *date_buf = (char *)arg;
    if (!date_buf) return;

    pthread_mutex_lock(&lv_mutex);
    if (ui_date2 && lv_obj_is_valid(ui_date2)) {
        lv_label_set_text(ui_date2, date_buf);
        if (small_font_initialized) {
            // 移除未受保护的样式应用 - lv_obj_add_style(ui_date2, &small_font_style, LV_PART_MAIN);
        } else {
            log_message(LOG_ERROR, "small_font_style未初始化");
        }
    } else {
        log_message(LOG_ERROR, "ui_date2对象无效");
    }
    pthread_mutex_unlock(&lv_mutex);
    free(date_buf); // 释放strdup分配的内存
}

/* 异步轮胎状态更新处理函数 */
typedef struct {
    int pos;
    float pressure;
    float temp;
} TireUpdateArgs;

/* 日志函数实现 */
// 添加日志互斥锁
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

void log_message(LogLevel level, const char *format, ...)
{
    pthread_mutex_lock(&log_mutex);
    
    const char *level_str[] = {"DEBUG", "INFO", "WARNING", "ERROR"};
    time_t now = time(NULL);
    char time_str[20];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));

    va_list args;
    va_start(args, format);

    // 在实际项目中，可以输出到文件或系统日志
    printf("[%s] [%s] ", time_str, level_str[level]);
    vprintf(format, args);
    printf("\n");

    va_end(args);
    pthread_mutex_unlock(&log_mutex);
}

/* 确保数据目录存在 */
bool ensure_data_directory_exists(void)
{
    char path[PATH_MAX];
    const char *home = getenv("HOME");
    snprintf(path, sizeof(path), "%s/.%s", home ? home : "/tmp", DATA_DIR_NAME);

    if (mkdir(path, 0700) == -1 && errno != EEXIST) {
        log_message(LOG_ERROR, "创建目录失败: %s", strerror(errno));
        return false;
    }
    return true;
}

// 实现路径函数
bool get_data_path(char *buf, size_t size)
{
    if (!ensure_data_directory_exists())
    {
        return false;
    }

    char *home = getenv("HOME");
    if (home)
    {
        snprintf(buf, size, "%s/.%s/%s", home, DATA_DIR_NAME, DATA_FILE_NAME);
    }
    else
    {
        snprintf(buf, size, "/tmp/%s/%s", DATA_DIR_NAME, DATA_FILE_NAME);
    }

    log_message(LOG_DEBUG, "数据文件路径: %s", buf);
    return true;
}

// 修复get_data_path函数闭合括号

bool backup_driving_data(void)
{
    system_state.backup_data = system_state.current_data;
    return true;
}

bool restore_driving_data(void)
{
    system_state.current_data = system_state.backup_data;
    return true;
}

bool load_driving_data() {
    FILE *fp = fopen(DATA_FILE_NAME, "rb");
    if (!fp) {
        return false;
    }

    DrivingData loaded_data;
    size_t read = fread(&loaded_data, sizeof(DrivingData), 1, fp);
    fclose(fp);

    if (read != 1) {
        log_message(LOG_ERROR, "数据加载失败: 读取数据不完整");
        return false;
    }
    
    // 验证数据合理性
    if (loaded_data.driving_distance < 0 || loaded_data.driving_distance > 1000000 || 
        loaded_data.total_distance < 0 || loaded_data.total_distance > 1000000 ||
        loaded_data.driving_time < 0 || loaded_data.driving_time > 100000 ||
        loaded_data.fuel_consumption < 0 || loaded_data.fuel_consumption > 50) {
        log_message(LOG_ERROR, "数据加载失败: 数据值超出合理范围");
        return false;
    }
    
    system_state.current_data = loaded_data;
    system_state.backup_data = loaded_data;
    system_state.data_modified = false;
    
    log_message(LOG_INFO, "数据加载成功: %d km, %d min, %.1f L/100km, %d km total", loaded_data.driving_distance, loaded_data.driving_time, loaded_data.fuel_consumption, loaded_data.total_distance);
    return true;
}

void* init_driving_data_thread(void* arg) {
    (void)arg;
    
    if (!init_driving_data()) {
        log_message(LOG_ERROR, "后台线程初始化行驶数据失败");
    }
    
    // 首次生成数据
    if (!generate_driving_data()) {
        log_message(LOG_WARNING, "首次数据生成失败");
    }
    
    return NULL;
}

// 消息框按钮事件处理函数
static void msgbox_btn_event_handler(lv_event_t *e) {
    lv_obj_t *msgbox = lv_event_get_user_data(e);
    if (lv_obj_is_valid(msgbox) && lv_event_get_code(e) == LV_EVENT_VALUE_CHANGED) {
        const char *txt = lv_msgbox_get_active_btn_text(msgbox);
        if (txt && strcmp(txt, "Confirm") == 0) {
            // 检查数据生成状态，避免竞态条件
            if (!atomic_load(&data_generation_in_progress)) {
                reset_driving_data();
                safe_async_call((void(*)(void*))update_display, NULL);
            } else {
                log_message(LOG_WARNING, "数据正在生成中，无法重置");
            }
        }
        lv_obj_del_async(msgbox);

    }
}

/* 长按清零处理函数 */
// 异步创建消息框的处理函数
static void create_clear_data_msgbox_async(void *arg)
{
    lv_obj_t *msgbox = lv_msgbox_create(
        NULL,                                  // 父对象（NULL表示无父对象）
        "Confirm",                                // 标题
        "Are you sure you want to clear your driving data?",               // 消息内容
        (const char *[]) {"Confirm", "Cancel", NULL}, // 按钮数组（必须以NULL结尾！）
        false
    );
    if (!msgbox) {
        log_message(LOG_ERROR, "Failed to create message box");
        return;
    }

    lv_obj_set_style_bg_color(msgbox, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_obj_set_size(msgbox, 300, 200);
    lv_obj_center(msgbox);
    
    // 事件处理
    // 移除重复的DELETE事件处理，避免冲突
    lv_obj_add_event_cb(msgbox, msgbox_btn_event_handler, LV_EVENT_VALUE_CHANGED, msgbox);
}

static void qrj_long_press_handler(lv_event_t *e)
{
    if (e->code == LV_EVENT_LONG_PRESSED)
    {
        safe_async_call(create_clear_data_msgbox_async, NULL);
    }
}

bool generate_driving_data(void) {
    // 原子操作检查是否已在生成数据
    if (atomic_exchange(&data_generation_in_progress, true)) {
        log_message(LOG_WARNING, "数据生成已在进行中，跳过此次调用");
        return false;
    }

    atomic_store(&data_generation_in_progress, true);
    log_message(LOG_DEBUG, "Entering generate_driving_data");
    
    SystemState *state = get_system_state();
    if (!state) {
        atomic_store(&data_generation_in_progress, false);
        return false;
    }

    // 加锁保护数据操作
    if (!LOCK_DATA()) {
        log_message(LOG_ERROR, "Failed to acquire data lock in generate_driving_data");
        atomic_store(&data_generation_in_progress, false);
        return false;
    }
    
    // 生成随机但合理的数据
    // 使用小幅度增量代替随机值，避免里程剧烈波动
    static uint32_t incremental_distance = 0;
    
    // 检测外部重置（如用户手动清零）
    if (state->current_data.driving_distance == 0 && incremental_distance != 0) {
        incremental_distance = 0;
    }
    
    incremental_distance += (rand() % 5); // 每次增加0-4km
    state->current_data.driving_distance = incremental_distance;
    // 限制最大里程，防止溢出
    if (state->current_data.driving_distance > 1000) {
        incremental_distance = 0;
        state->current_data.driving_distance = 0;
    }
    
    // 确保行驶时间与里程成比例 (假设平均速度约70km/h)
    state->current_data.driving_time = 7 + (state->current_data.driving_distance - MIN_DISTANCE) / 70;
    state->current_data.driving_time = CLAMP(state->current_data.driving_time, MIN_TIME, MAX_TIME);
    
    // 油耗与里程成比例 (假设油耗随里程增加而降低)
    state->current_data.fuel_consumption = 46.0f - 
        ((state->current_data.driving_distance - MIN_DISTANCE) * 0.01f);
    state->current_data.fuel_consumption = CLAMP(state->current_data.fuel_consumption, MIN_FUEL, MAX_FUEL);
    
    // 总里程必须大于当前行驶里程
    // 确保总里程不超过15000上限
    int max_possible_total = 15000 - state->current_data.driving_distance;
    if (max_possible_total < 0) max_possible_total = 0;
    state->current_data.total_distance = state->current_data.driving_distance + 
        (rand() % (max_possible_total + 1));
    
    state->current_data.last_update = time(NULL);
    state->data_modified = true;

    sanitize_driving_data(&state->current_data);
    bool valid = validate_driving_data(&state->current_data);
    
    UNLOCK_DATA();
    
    // 重置原子标志
    atomic_store(&data_generation_in_progress, false);
    return valid;
}

bool init_driving_data(void)
{
    log_message(LOG_DEBUG, "初始化驾驶数据");
    return true;
}

// 添加定时器回调函数
static void weather_timer_cb(lv_timer_t* timer) {
    if(!timer || !timer->user_data) {
        printf("Invalid timer callback\n");
        return;
    }
    char* api_url = (char*)timer->user_data;
    printf("Fetching weather data from: %s\n", api_url);
    http_get_async(api_url, http_response_handler);
}

/* 控制台主线程 */
void *iu_main(void *arg) {
    init_mutex(); // 确保互斥锁初始化
    char input[256]; // 增大缓冲区防止溢出
    size_t input_len;

  // 只打印一次菜单
    if (current_mode == CONSOLE_MODE) {
        print_console_menu();
    }

    while (1)
    {
        // 使用select实现带超时的非阻塞输入
        fd_set read_fds;
        // struct timeval timeout;
        struct timeval timeout = {0, 100000}; // 100ms
        int ret;

        FD_ZERO(&read_fds);
        FD_SET(STDIN_FILENO, &read_fds);     

        ret = select(STDIN_FILENO + 1, &read_fds, NULL, NULL, &timeout);
        if (ret == -1)
        {
            perror("select error");
            continue;
        }
        else if (ret == 0)
        {
            // 超时，继续循环检查
            continue;
        }

        is_console_input_active = true; // 标记输入开始
        if (fgets(input, sizeof(input), stdin) == NULL)
        {
            is_console_input_active = false; // 标记输入结束
            continue;
        }
        input_len = strlen(input);
        // 检查是否有换行符，如果没有说明输入溢出
        if (input_len > 0 && input[input_len - 1] != '\n' && input_len == sizeof(input) - 1)
        {
            // 清理剩余输入
            int c;
            while ((c = getchar()) != '\n' && c != EOF);
        }
        input[strcspn(input, "\n")] = '\0';

        if (process_command(input)) {
            continue;
        }

        if (current_mode == DATA_VIEW_MODE) {
            printf("无效命令。请输入 'fanhui' 返回控制台。\n");
            continue;
        }

        // 处理速度设置命令
        if (strncmp(input, "speed", 5) == 0)
        {
            // 解析命令，跳过"speed "
            char *token = strtok(input + 6, " ");
            if (token == NULL)
            {
                printf("命令格式错误！使用: speed [0-240]\n");
                continue;
            }

            char *endptr;
            long speed_val = strtol(token, &endptr, 10);
            if (endptr == token || *endptr != '\0' || speed_val < 0 || speed_val > 240)
            {
                printf("速度值必须在0~240之间！\n");
                continue;
            }

            // 调用动画函数更新指针
            safe_async_call((void(*)(void*))update_speed_pointer, (void*)(intptr_t)speed_val);
            printf("设置速度：%ld km/h\n", speed_val);
        }

        // 处理转速度设置命令
        if (strncmp(input, "rev", 3) == 0)
        {
            // 解析命令，跳过"rev "
            char *token = strtok(input + 4, " ");
            if (token == NULL)
            {
                printf("命令格式错误！使用: rev [0-8000]\n");
                continue;
            }

            char *endptr;
            long rev_val = strtol(token, &endptr, 10);
            if (endptr == token || *endptr != '\0' || rev_val < 0 || rev_val > 8000)
            {
                printf("转速度值必须在0~8000之间！\n");
                continue;
            }

            // 调用动画函数更新指针
            safe_async_call((void(*)(void*))update_revspeed_pointer, (void*)(intptr_t)rev_val);
            printf("设置转速度：%ld rpm\n", rev_val);
        }

        // 处理油耗设置命令
        if (strncmp(input, "youhao", 6) == 0)
        {
            // 解析命令，跳过"youhao "
            char *token = strtok(input + 7, " ");
            if (token == NULL)
            {
                printf("命令格式错误！使用: youhao [0.0-1.0]\n");
                continue;
            }

            float fuel_value = atof(token);
            if (fuel_value < 0.0f || fuel_value > 1.0f)
            {
                printf("油耗值必须在0.0~1.0之间！\n");
                continue;
            }

            // 调用动画函数更新指针 - 修复参数传递错误
            float *fuel_param = malloc(sizeof(float));
            if (fuel_param == NULL) {
                printf("内存分配失败\n");
                continue;
            }
            *fuel_param = fuel_value;
            safe_async_call((void(*)(void*))update_fuel_consumption_async, fuel_param);
            printf("设置油耗值：%.2f L/100km\n", fuel_value);
        }

        // 处理冷却液温度设置命令
        if (strncmp(input, "coolant", 7) == 0)
        {
            // 解析命令，跳过"coolant"
            char *token = strtok(input + 8, " ");
            if (token == NULL)
            {
                printf("命令格式错误！使用: coolant [0-120]\n");
                continue;
            }

            char *endptr;
            long temp_val = strtol(token, &endptr, 10);
            if (endptr == token || *endptr != '\0' || temp_val < 0 || temp_val > 120)
            {
                printf("温度值必须在0~120之间！\n");
                continue;
            }

            // 调用动画函数更新指针
            safe_async_call((void(*)(void*))update_coolant_temp, (void*)(intptr_t)temp_val);
            printf("设置冷却液温度：%ld℃\n", temp_val);
        }

        // 处理换挡指令
        if (strlen(input) == 1)
        {
            Gear new_gear;
            switch (input[0])
            {
            case 'p':
            case 'P':
                new_gear = GEAR_P;
                break;
            case 'r':
            case 'R':
                new_gear = GEAR_R;
                break;
            case 'n':
            case 'N':
                new_gear = GEAR_N;
                break;
            case 'd':
            case 'D':
                new_gear = GEAR_D;
                break;
            case 's':
            case 'S':
                new_gear = GEAR_S;
                break;
            default:
                new_gear = get_current_gear(); // 保持当前档位
                break;
            }

            if (new_gear != get_current_gear())
            {
                safe_async_call((void(*)(void*))handle_gear_change, (void*)(intptr_t)new_gear);
            }
        }

        // 处理驾驶模式切换命令
        if (strlen(input) == 1 && isdigit(input[0]))
        {
            int mode_num = input[0] - '0';
            if (mode_num >= 0 && mode_num <= 4)
            {
                safe_async_call((void(*)(void*))change_driving_mode, (void*)(intptr_t)mode_num);
            }
            else
            {
                printf("无效的驾驶模式编号！\n");
            }
        }
        

        // 处理轮胎设置命令
        if (strncmp(input, "tire", 4) == 0)
        {
            char *token = strtok(input + 5, " ");
            if (!token)
            {
                printf("缺少轮胎位置参数！\n");
                continue;
            }
            int position = atoi(token) - 1;
            if (position < 0 || position > 3)
            {
                printf("轮胎位置必须在1-4之间！\n");
                continue;
            }
            token = strtok(NULL, " ");
            if (!token)
            {
                printf("缺少胎压参数！\n");
                continue;
            }
            char *endptr;
            long pressure_val = strtol(token, &endptr, 10);
            if (endptr == token || *endptr != '\0' || pressure_val < 0 || pressure_val > 300)
            {
                printf("胎压值必须在0~300之间！\n");
                continue;
            }
            int pressure = (int)pressure_val;

            token = strtok(NULL, " ");
            if (!token)
            {
                printf("缺少温度参数！\n");
                continue;
            }
            long temp_val = strtol(token, &endptr, 10);
            if (endptr == token || *endptr != '\0' || temp_val < -40 || temp_val > 120)
            {
                printf("温度值必须在-40~120之间！\n");
                continue;
            }
            int temperature = (int)temp_val;

    // 合并胎压和温度更新为单次调用，避免异步竞争
    set_tire_pressure_and_temperature(position, pressure, temperature);

            printf("设置轮胎%d: 胎压=%dkPa, 温度=%d°C\n",
                   position + 1, pressure, temperature);
        }
        is_console_input_active = false; // 标记输入结束

        if (strncmp(input, "on zuosan", 9) == 0)
        {
            toggle_left_turn_signal(true);
            printf("左转向灯已开启\n");
        }
        else if (strncmp(input, "off zuosan", 10) == 0)
        {
            toggle_left_turn_signal(false);
            printf("左转向灯已关闭\n");
        }

        if (strncmp(input, "on yousan", 9) == 0)
        {
            toggle_right_turn_signal(true);
            printf("右转向灯已开启\n");
        }
        else if (strncmp(input, "off yousan", 10) == 0)
        {
            toggle_right_turn_signal(false);
            printf("右转向灯已关闭\n");
        }

        if (strncmp(input, "on shuangshan", 13) == 0)
        {
            safe_async_call((void(*)(void*))toggle_hazard_lights, (void*)true);
            printf("双闪灯已开启\n");
        }
        else if (strncmp(input, "off shuangshan", 14) == 0)
        {
            safe_async_call((void(*)(void*))toggle_hazard_lights, (void*)false);
            printf("双闪灯已关闭\n");
        }

        // 处理指示灯控制命令
        else if (strncmp(input, "on ", 3) == 0 || strncmp(input, "off ", 4) == 0)
        {
            char *cmd = strtok(input, " ");
            char *indicator_name = strtok(NULL, " \n");

            if (cmd && indicator_name)
            {
                bool new_state = (strcmp(cmd, "on") == 0);

                if (strcmp(indicator_name, "left") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                left_turn_signal_on = new_state;
                pthread_mutex_unlock(&indicator_mutex);
                printf("左转向灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "right") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                right_turn_signal_on = new_state;
                pthread_mutex_unlock(&indicator_mutex);
                printf("右转向灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "jsd") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                hazard_lights_on = new_state;
                pthread_mutex_unlock(&indicator_mutex);
                printf("警示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "qianchegai") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    qianchegai_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("前车盖灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "houchegai") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    houchegai_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("后车盖灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "aqdjs") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    aqdjs_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("安全带警示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "shache") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    shache_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("刹车灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "fdj") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    fadongji_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("发动机提示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "jinguangdeng") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    jinguangdeng_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("近光灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "yuanguangdeng") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    yuanguangdeng_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("远光灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "aqqn") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    aqqn_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("安全气囊打开提示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "chemen") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    chemen_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("车门打开提示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "qwz") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    qwzd_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("前位置灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "hwz") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    hwzd_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("后位置灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "youya") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    youya_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("油压指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "qwd") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    qwd_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("前雾灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "hwd") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    hwd_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("后雾灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "ss") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    shuangshan_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("双闪灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "abs") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    abs_active = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("ABS灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "eco") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    eco_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("eco指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "zhudong") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    zhudong_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("驻动指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "dlfz") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    dlfz_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("道路辅助 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "yld") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    youliangdeng_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("油量指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "cldc") == 0)
                {
                    cldc_on = new_state;
                    printf("车辆电池指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "clzt") == 0)
                {
                    cheliangzitai_on = new_state;
                    printf("车辆姿态 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "clxh") == 0)
                {
                    cheliangxinhao_on = new_state;
                    printf("车辆信号指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "cstx") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    chaosutixing_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("超速提醒 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "yugua") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    yugua_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("雨刮器指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "clxs") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    xiansu_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("车辆限速 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "aqzs") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    aqzsd_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("安全指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "clw") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    chelianwang_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("车联网 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "zdjs") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    zdjs_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("自动驾驶 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "lqy") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    lqyd_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("冷却液温度指示灯 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "clgy") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    clgy_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("车辆感应 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "tyjg") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    tyjg_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("胎压警告 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "ldxt") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    ldxt_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("雷达系统 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "ysxt") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    ysxt_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("夜视系统 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "zny") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    zny_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("智能眼系统 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "zqtxh") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    zqtxh_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("左前胎信号 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "zhtxh") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    zhtxh_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("左后胎信号 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "yqtxh") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    yqtxh_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("右前胎信号 %s\n", new_state ? "开启" : "关闭");
                }
                else if (strcmp(indicator_name, "yhtxh") == 0)
                {
                    pthread_mutex_lock(&indicator_mutex);
                    yhtxh_on = new_state;
                    pthread_mutex_unlock(&indicator_mutex);
                    printf("右后胎信号 %s\n", new_state ? "开启" : "关闭");
                }

                else
                {
                    printf("未知指示灯名称\n");
                }

                // 更新所有指示灯状态
                safe_async_call((void(*)(void*))update_all_indicators, NULL);
            }
        }
        // 处理退出命令
        else if (strcmp(input, "exit") == 0 || strcmp(input, "q") == 0)
        {
            exit(0);
        }
        else
        {
            printf("无效命令!\n");
        }

        usleep(5000);

        is_console_input_active = false;
    }
    return NULL;
}
void print_console_menu(void) {
    pthread_mutex_lock(&lv_mutex);
    
    printf("\n======= 车载仪表控制台 =======\n");
    printf("设置速度: speed [0-240]\n");
    printf("设置转速: rev [0-8000]\n");
    printf("换挡: p(驻车)/r(倒车)/n(空挡)/d(前进)/s(运动)\n");
    printf("驾驶模式: 0(普通)/1(环保)/2(竞速)/3(夜间)/4(智能)\n");
    printf("指示灯控制: on/off [指示灯名称]\n");
    printf("左转向灯开启/关闭: on zuosan/off zuosan\n");
    printf("右转向灯开启/关闭: on yousan/off yousan\n");
    printf("双闪灯开启/关闭: on shuangshan/off shuangshan\n");
    printf("设置冷却液温度:coolant[0-120]\n");
    printf("请输入命令(youhao [0.0-1.0]):\n");
    printf("轮胎设置: tire [位置(1-4)] [胎压] [温度]\n");
    printf("查看数据: check shuju\n");
    printf("退出: q 或 exit\n");
    printf("输入命令: ");
    fflush(stdout);
    
    pthread_mutex_unlock(&lv_mutex);
}